<template>
  <div class="app-container">
    <el-row>
      <el-col :span="4">
        <strong style="font-size: 20px;">
          垫付
        </strong>
      </el-col>
      <el-col :span="20" align="center">
        <strong style="font-size: 16px;">
          账户余额:{{ balance.user }}
        </strong>
        <strong style="font-size: 16px;">
          酒代余额:{{ balance.wineAgent }}
        </strong>
        <strong style="font-size: 16px;">
          欠款:{{ balance.borrow }}
        </strong>
      </el-col>
    </el-row>

    <el-row style="padding-top:10px">
      <el-col :span="24" align="right">
        <span style="margin-right: .5em">
          <span>金额</span>
          <el-input v-model="form.amount" style="padding:0px 10px;width:400px" type="number" />
        </span>
        <span style="margin-right: .5em">
          <el-button :loading="loading" type="primary" @click="borrow(0)">{{ loading ? '提交中 ...' : '借入' }}</el-button>
        </span>
        <span style="margin-right: .5em">
          <el-button :loading="loading" type="danger" @click="borrow(1)">{{ loading ? '提交中 ...' : '归还' }}</el-button>
        </span>
        <span style="margin-right: .5em">
          <el-date-picker
            v-model="search.beforeTime"
            type="date"
            placeholder="开始日期"
            style="width: 150px;"
            size="medium"
            :editable="false"
            value-format="yyyy-MM-dd"
          />
        </span>
        <span style="margin-right: .5em">
          <el-date-picker
            v-model="search.afterTime"
            type="date"
            placeholder="结束日期"
            style="width: 150px;"
            size="medium"
            :editable="false"
            value-format="yyyy-MM-dd"
          />
        </span>

        <el-button
          size="medium"
          icon="el-icon-search"
          style="margin-right: 1em"
          circle
          @click="getShowList()"
        />
      </el-col>
    </el-row>

    <el-row>
      <el-table
        v-loading="loading"
        :data="showList.slice((pager.page - 1) * pager.limit, pager.page * pager.limit)"
        element-loading-text="加载中..."
        fit
        lazy
        stripe
        highlight-current-row
        style="width: 100%"
      >
        <el-table-column label="#" type="index" />
        <el-table-column prop="amount" label="金额" />
        <el-table-column prop="comment" label="备注" />
        <el-table-column label="创建时间">
          <template slot-scope="scope">
            <span>{{ new Date(scope.row.createdTime ) | dateFormat('YYYY-MM-DD HH:mm:ss') }}</span>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <el-row>
      <div class="block">
        <el-pagination
          :current-page.sync="pager.page"
          :page-sizes="[20, 50, 100, 300]"
          :page-size="pager.limit"
          layout="total, sizes, prev, pager, next, jumper"
          :total="showList.length"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-row>
  </div>
</template>

<script>
export default {
  data() {
    return {
      form: {
        amount: null
      },
      loading: false,
      user: 0,
      wineAgent: 0,

      list: [],
      showList: [],
      search: {
        beforeTime: null,
        afterTime: null
      },
      pager: {
        page: 1,
        limit: 20
      },
      balance: {
        user: 0,
        wineAgent: 0,
        borrow: 0
      }
    }
  },
  async created() {
    const user = await this.axios.get(`/api/user`, { params: {
      '@expands': `['entity.officer.store']`
    }})
    this.user = user.data.officer?.__metadata.store?.__metadata.user?.id
    this.wineAgent = user.data.officer?.__metadata.store?.__metadata.wineAgent?.id

    this.filterGenerate()
    this.dataProcessor()
    this.getBalance()
  },
  methods: {
    clearSearch() {
      this.pager.page = 1
      this.search.beforeTime = null
      this.search.afterTime = null
      this.form.amount = null
      this.dataProcessor()
      this.getBalance()
    },
    getBalance() {
      if (!this.user) {
        this.$message.error('获取主账号信息失败！')
        return
      }
      if (!this.wineAgent) {
        this.$message.error('获取酒代账号信息失败！')
        return
      }
      this.axios.get(`/officer/balances`, { params: {
        '@filter': `entity.getUser().getId() in [${this.user},${this.wineAgent}]`
      }}).then(res => {
        const userBalance = res.data.find(v => v.user.id === this.user)
        const wineBalance = res.data.find(v => v.user.id === this.wineAgent)
        if (userBalance) {
          this.balance.user = userBalance.amount
        }
        if (wineBalance) {
          this.balance.wineAgent = wineBalance.amount
        }
      })
    },
    borrow(type) {
      if (!this.form.amount > 0) {
        this.$message.error('请填写金额')
        return
      }
      if (!this.wineAgent > 0) {
        this.$message.error('获取借入信息失败')
        return
      }

      this.loading = true
      let url = '/officer/loans/'
      if (type > 0) {
        url += 'return'
      } else {
        url += 'borrow'
      }
      url += `/${this.wineAgent}/amount/${this.form.amount}`
      this.axios.post(url).then(res => {
        this.$message.success('执行成功')
        this.clearSearch()
      }).finally(() => {
        this.loading = false
      })
    },
    filterGenerate() {
      this.filter = {
        '@filter': `entity.getFrom().getId() == ${this.wineAgent} && entity.getTo().getId() == ${this.user}`,
        '@expands': '["entity.transactions"]'
      }
    },
    dataProcessor() {
      this.loading = true
      // table数据
      this.axios.get(`/officer/loans`, {
        params: Object.assign(
          {},
          this.filter,
          this.pager
        )
      }).then(res => {
        const list = []
        if (res.data.length > 0) {
          this.balance.borrow = res.data[0].amount
          for (var i of res.data[0].transactions) {
            list.push(i.__metadata)
          }
          list.sort((a, b) => {
            return new Date(b.createdTime) - new Date(a.createdTime)
          })
        }
        this.list = list
        this.getShowList()
        this.loading = false
      })
    },
    // Pager size changed
    handleSizeChange(val) {
      this.pager.page = 1
      this.pager.limit = val
      this.getShowList()
    },

    // Pager page changed
    handleCurrentChange(val) {
      this.pager.page = val
      this.getShowList()
    },

    getShowList() {
      let showList = this.list
      if (this.search.beforeTime) {
        showList = showList.filter(v => {
          return new Date(v.createdTime) >= new Date(this.search.beforeTime + ' 00:00:00')
        })
      }
      if (this.search.afterTime) {
        showList = showList.filter(v => {
          return new Date(v.createdTime) <= new Date(this.search.afterTime + ' 23:59:59')
        })
      }
      this.showList = showList
    }
  }
}
</script>
